package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type searchInfo struct {
	SubjectParentID int `json:"subjectParentId"`
	SubjectID       int `json:"subjectId"`
}

func GetFrontCourseInfo(ctx *gin.Context) {
	id := ctx.Param("id")

	// 查询课程信息
	course, _ := eduCourseService.Select(id)
	// 更新课程学习数
	course.BuyCount = course.BuyCount + 1
	eduCourseService.Update(course)
	// 查询分类信息
	spid := strconv.Itoa(course.SubjectParentID)
	sid := strconv.Itoa(course.SubjectID)
	parentSubject, _ := eduSubjectService.SelectByCourseID(spid)
	subject, _ := eduSubjectService.SelectByCourseID(sid)
	// 查询教师信息
	tid := strconv.Itoa(course.TeacherID)
	teacher, _ := eduTeacherService.SelectByID(tid)
	// 查询课程描述信息
	description, _ := eduCourseDescriptionService.SelectByCourseID(id)
	// 查询章节小节信息
	chapterVideo, _ := eduChapterService.GetAllChapterVideo(id)

	courseMap := make(map[string]interface{})
	courseMap["cover"] = course.Cover
	courseMap["title"] = course.Title
	courseMap["price"] = course.Price
	courseMap["teacherName"] = teacher.Name
	courseMap["buyCount"] = course.BuyCount
	courseMap["lessonNum"] = course.LessonNum
	courseMap["viewCount"] = course.ViewCount
	courseMap["description"] = description.Description
	courseMap["avatar"] = teacher.Avatar
	courseMap["intro"] = teacher.Intro
	courseMap["subjectLevelOne"] = parentSubject.Title
	courseMap["subjectLevelTwo"] = subject.Title
	courseMap["teacherId"] = teacher.ID

	ctx.JSON(http.StatusOK, gin.H{
		"code":          20000,
		"courseWebVo":   courseMap,
		"chapterVoList": chapterVideo,
	})
	return
}

func GetFrontCourseList(ctx *gin.Context) {
	page := ctx.Param("page")
	pageSize := ctx.Param("pageSize")

	search := &searchInfo{}
	ctx.ShouldBind(&search)

	p, _ := strconv.Atoi(page)
	ps, _ := strconv.Atoi(pageSize)
	count, _ := eduCourseService.SelectCourseCount()

	// 判断是否有前一页
	hasPrevious := false
	if page != "1" {
		hasPrevious = true
	}

	// 判断是否有后一页
	hasNext := true
	t := count / int64(ps)
	if int64(p)-1 == t {
		hasNext = false
	}

	// 计算所有的页数
	pages := make([]int, 0)
	for i := 0; i <= int(t); i++ {
		pages = append(pages, i+1)
	}

	courses, _ := eduCourseService.SelectFrontCourse(p, ps, search.SubjectParentID, search.SubjectID)
	dataMap := make(map[string]interface{})
	dataMap["total"] = count
	dataMap["items"] = courses
	dataMap["hasPrevious"] = hasPrevious
	dataMap["current"] = page
	dataMap["hasNext"] = hasNext
	dataMap["pages"] = pages
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"data": dataMap,
	})
	return
}
